package com.shj.service;


import com.shj.mapper.SysUserRoleDao;
import com.shj.model.SysUserRole;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description 用户角色
 * @Author songhuajian
 * @Date 2020/1/12 23:08
 **/
@Slf4j
@Service("sysUserRoleService")
public class SysUserRoleService {

    @Resource
    private SysUserRoleDao sysUserRoleDao;

    /**
     * @description 根据用户编号查询角色
     * @author songhuajian
     * @date 2020/1/12 23:19
     */
    public List<SysUserRole> findByUserId(String userId){
        return sysUserRoleDao.queryByUserId(userId);
    }

    /**
     * @Description 添加用户角色
     * @author songhuajian
     * @date 2020/4/3 20:15
     */
    @Transactional(rollbackFor = Exception.class)
    public void addUserRole(List<String> roles, String userId) throws Exception {
        int len = roles.size();
        // 最后一项时用户编号，所以长度要减一
        for (int i=0;i<len-1;i++) {
            String roleId = roles.get(i);
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userId);
            sysUserRole.setRoleId(roleId);
            sysUserRoleDao.insert(sysUserRole);
        }
    }

    /**
     * @Description 更新用户角色
     * @author songhuajian
     * @date 2020/4/10 17:12
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateUserRole(List<String> roles, String userId) {
        // 删除数据库中的关联
        sysUserRoleDao.deleteByUserId(userId);
        // 新添加关联
        for (String roleId : roles) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(roleId);
            sysUserRole.setUserId(userId);
            sysUserRoleDao.insert(sysUserRole);
        }
    }
}
